import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login/login'
import { convertRouter } from '@/utils/handleRoutes'
import store from '../store'

//---- 解决重定义警告
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
    return originalPush.call(this, location).catch(err => err)
}
//--- end 

Vue.use(VueRouter)

const routes = [{
    path: '/',
    name: 'index',
    component: () =>
        import('@/layouts/HeadLayout')
},
{ path: '/login', component: Login }
]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes: routes
})

function getPageTitle (pageTitle) {
    if (pageTitle) {
        return `${pageTitle}-hawk运维管理平台`
    }
    return `hawk运维管理平台`
}

//挂载路由导航守卫
router.beforeEach((to, from, next) => {
    // console.log('from : ', from );
    // console.log('to : ', to );
    document.title = getPageTitle(to.meta.title)
    if (to.path === '/login') return next()

    const token = window.localStorage.getItem('token')
    if (!token) return next('/login')

    if (to.path.split('/').length > 2) {
        store.dispatch('history/setHistory', to.path)
    }

    if (router.getRoutes().length < 3) {
        const menus = JSON.parse(localStorage.getItem('menu'));
        console.log(menus);
        let routes = convertRouter(menus);
        for (const route of routes) {
            router.addRoute("index", route)
        }
        return next({ ...to, replace: true })
    }

    // console.log(window.routeReload);
    if(!window.routeReload && to.path == '/home' && from.path != '/'){
        window.routeReload = true
        return next(from)
    }
    return next()
})
export default { router, routes }